/*-
 * RequestBodyDeserializerExt.java
 *
 * Date: 2017年1月5日
 * Time: 下午3:12:40
 *
 * 版权所有©2012-2013 rengh
 */

package com.lmx.kathHack.serialize;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

import io.katharsis.jackson.exception.ParametersDeserializationException;
import io.katharsis.request.dto.DataBody;

public class ResourcePayloadDatasDeserializer extends JsonDeserializer<PayloadDatas> {
	private static final String DATA_FIELD_NAME = "data";

	@Override
	public PayloadDatas deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
		JsonNode node = jp.readValueAsTree();
		if (node == null) {
			return null;
		}
		PayloadDatas payloadDatas = new PayloadDatas();

		Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
		while (fields.hasNext()) {
			Map.Entry<String, JsonNode> field = fields.next();
			Object value;
			if (field.getValue() == null) {
				throw new ParametersDeserializationException("Attribute field cannot be null for: " + field.getKey());
			} else if (field.getValue().get(DATA_FIELD_NAME) == null) {
				if (field.getKey().equals("reverse")) {
					String fieldString = field.toString();
					String[] temp = fieldString.split(":");
					value = temp[1].replace("\"", "").replace("}", "");
				} else {
					value = null;
				}
			} else if (field.getValue().get(DATA_FIELD_NAME).isArray()) {
				JsonNode fieldData = field.getValue().get(DATA_FIELD_NAME);
				Iterator<JsonNode> nodeIterator = fieldData.iterator();
				List<DataBody> linkageDatas = new LinkedList<>();

				while (nodeIterator.hasNext()) {
					DataBody newLinkageData = jp.getCodec().treeToValue(nodeIterator.next(), DataBody.class);
					linkageDatas.add(newLinkageData);
				}
				value = linkageDatas;
			} else {
				DataBody kathValue = jp.getCodec().treeToValue(field.getValue().get(DATA_FIELD_NAME), DataBody.class);
				value = kathValue;
			}
			payloadDatas.setAdditionalProperty(field.getKey(), value);
		}

		return payloadDatas;
	}
}